from subprocess import call
import os
import cdsapi
from datetime import datetime

t = datetime(
            year = 2025, 
            month = 1,
            day = 1,  
            hour = 0, 
            minute = 0
        )

IDM_path = os.path.join(os.getcwd(), 'downloader_provider', 'IDM', 'IDMan.exe')
upper_variables = ['10m_u_component_of_wind', '10m_v_component_of_wind', '2m_temperature', 'mean_sea_level_pressure']

def out_url(t):

    dataset = "reanalysis-era5-single-levels"
    request = {
        "product_type": ["reanalysis"],
        "variable": upper_variables,
        "year": str(t.year),
        "month": str(t.month),
        "day": str(t.day),
        "time": t.strftime('%H:%M'),
        "data_format": "netcdf",
        "download_format": "unarchived"
    }
    c = cdsapi.Client()
    surface_url = c.retrieve(dataset, request).location
    return surface_url

def downloader_IDM(DownPath, local_file_name, url):
    os.startfile(IDM_path)
    IDM = IDM_path 
    urlList = [url]
    for ul in urlList:
        call([IDM, '/d', ul, '/p', DownPath, '/f', local_file_name, '/n', '/a'])
    call([IDM, '/s'])

url = out_url(t)
forecasts_dir = os.path.join(os.getcwd(), 'forecasts', t.strftime("%Y-%m-%d-%H-%M"))
os.makedirs(forecasts_dir, exist_ok=True)

downloader_IDM(forecasts_dir, 
            'surface.nc', 
            url
            )